<template>
  <div class="add-app-dialog">

    <el-dialog
            v-model="dialogVisible"
            :before-close="handleClose"
            title="添加未规划终端"
            width="500px"
    >

      <el-form
              ref="ruleForm"
              :model="formData"
              :rules="rules"
              class="demo-ruleForm"
              label-width="140px"
              size="small"
      >
        <el-form-item label="产品信息">
          {{getProductName(propsProduct)}}
        </el-form-item>

        <el-form-item label="终端名称" prop="terminalName">
          <!--                    <el-input v-model="formData.name" placeholder="请输入终端名称"></el-input>-->

          <el-autocomplete
                  v-model="formData.terminalName"
                  :fetch-suggestions="querySearchAsync"
                  placeholder="请输入终端名称"
                  @blur="nameBlur"
                  @select="handleSelect"
          />
        </el-form-item>

        <el-form-item v-if="selectData && selectData.errorStatus">
          <span style="color:red">{{ errMap[selectData.errorStatus] }}</span>
        </el-form-item>

        <el-form-item v-else-if="isRepeat">
          <span style="color:red">终端已添加</span>
        </el-form-item>

        <el-form-item label="所在地区">
          <span>{{ formData.area }}</span>
          <!--                    <el-input v-model="formData.area"></el-input>-->
        </el-form-item>

        <el-form-item label="终端价：" prop="terminalPrice">

          <div style="display: flex;align-items: center;justify-content: space-between">
            <app-price-popover ref="pricePop" :props-product="copyData" @confirm="priceConfirm">
              <el-select v-model="formData.terminalPrice" placeholder="请选择终端价" style="width: 250px" @clear="priceClear"
                         @focus="priceFocus">
                <template #empty/>
              </el-select>
            </app-price-popover>

            <div style=" text-align: center">
              元
              <span v-if="propsProduct.sellUnit">
                  /{{ getLabel("sell_unit", propsProduct.sellUnit) }}</span>
            </div>
          </div>


        </el-form-item>

        <el-form-item v-if="formData.accessMode" label="准入模式">
          <span>{{ getLabel('access_mode', formData.accessMode) }}</span>
        </el-form-item>

        <el-form-item label="开发期限截止日期" prop="date">
          <date-picker v-model:date="formData.date" :disabled-date="disabledDate" placeholder="请选择截止日期"
                       @change="dateChange"/>
        </el-form-item>

        <el-form-item label="开发保证金" prop="devEarnestMoney">
          <el-input v-model.number="formData.devEarnestMoney" oninput="value=value.replace(/[^\d]/g,'')"
                    placeholder="请输入开发保证金"/>
        </el-form-item>

        <!--        <el-form-item label="最低销量">-->

        <!--          <el-input v-model.number="formData.minSale" oninput="value=value.replace(/[^\d]/g,'')" placeholder="请输入最低销量">-->
        <!--            <template #append>-->
        <!--              <span v-if="propsProduct.sellUnit"-->
        <!--                    style="margin-right: 10px">{{ getLabel('sell_unit', propsProduct.sellUnit) }}/</span>-->
        <!--              <el-select v-model="formData.minSaleUnit" placeholder="" style="width: 80px">-->
        <!--                <el-option-->
        <!--                    v-for="item in options"-->
        <!--                    :key="item.value"-->
        <!--                    :label="item.label"-->
        <!--                    :value="item.value"-->
        <!--                />-->
        <!--              </el-select>-->
        <!--            </template>-->
        <!--          </el-input>-->

        <!--        </el-form-item>-->

        <!--        <el-form-item label="销量保证金" prop="sellEarnestMoney">-->

        <!--          <el-input v-model.number="formData.sellEarnestMoney" clearable-->
        <!--                    oninput="value=value.replace(/[^\d]/g,'')" placeholder="请输入销量保证金" @blur="salesPriceBlur"/>-->

        <!--        </el-form-item>-->


      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleClose" size="small">取消</el-button>
          <el-button type="primary" @click="addClick" size="small">添加并继续</el-button>
          <el-button type="primary" @click="dialogConfirm" size="small">添加</el-button>
        </div>
      </template>
    </el-dialog>

  </div>
</template>

<script>
  import {crmStore} from '@CRM/store'
  import {defineComponent, getCurrentInstance, inject, reactive, ref, toRefs} from 'vue'

  export default defineComponent({
    name: 'addTerminalDialog',
    props: {
      list: {
        type: Array,
        default: []
      },
      propsProduct: {
        type: Object,
        default: {}
      },
    },
    setup(props, {emit}) {
      const currentInstance = getCurrentInstance()
      const api = inject('api')

      var isRepeat = ref(false)
      var ruleForm = ref(null)
      var dialogVisible = ref(false)
      var pricePop = ref(null)
      var errMap = ref({})
      var selectData = ref({})
      const options = crmStore.getters['dictionary/getDictionary']['sell_num_unit']
      const sellOptions = crmStore.getters['dictionary/getDictionary']['sales_volume']

      const rules = ref({
        terminalName: [
          {
            required: true,
            message: '请输入终端名称',
            trigger: 'change',
          },
        ],
        devEarnestMoney: [
          {
            required: true,
            message: '请输入开发保证金',
            trigger: 'blur',
          },
        ],
        date: [
          {
            type: 'date',
            required: true,
            message: '请选择结束日期',
            trigger: 'change',
          },
        ],
        terminalPrice: [
          {
            required: true,
            message: '请选择终端价',
            trigger: 'change',
          },
        ],
        salesVolume: [
          {
            required: true,
            message: '请选择营销体量',
            trigger: 'change',
          },
        ]
      })
      var data = reactive({
        copyData: {}
      })

      var formData = reactive({
        terminalId: '',
        terminalName: '',
        terminalType: '',
        area: '',
        date: '',
        expireTime: '',
        devEarnestMoney: '',
        exploitStr: '',
        minSale: '',
        minSaleUnit: '1',
        sellEarnestMoney: '',
        remark: '',
        terminalPrice: '',
        productPriceId: 0,
        accessMode: '',
        salesVolume: '',
      })

      const disabledDate = (time) => {
        return !(time.getTime() > Date.now())
      }

      const handleClose = () => {
        isRepeat.value = false
        formData.area = ''
        formData.minSale = ''
        formData.accessMode = ''
        formData.salesVolume = ''
        selectData.value = {}
        ruleForm.value.resetFields()
        setTimeout(() => {
          ruleForm.value.clearValidate()
          dialogVisible.value = false
        }, 100)
      }

      const addClick = () => {
        if (selectData.value.errorStatus) {
          currentInstance.proxy.customMessage({type: 'error', message: errMap.value[selectData.value.errorStatus]})
          return
        } else if (isRepeat.value) {
          currentInstance.proxy.customMessage({type: 'error', message: '终端已添加'})
          return
        }
        ruleForm.value.validate((val) => {
          if (val) {
            formData.exploitPrice = '¥' + formData.devEarnestMoney
            formData.devEarnestMoney = Number(formData.devEarnestMoney)
            if (formData.sellEarnestMoney) {
              formData.salesStr = '¥' + formData.sellEarnestMoney
            }
            formData.sellEarnestMoney = Number(formData.sellEarnestMoney)
            formData.minSale = Number(formData.minSale)

            emit('confirm', {...formData})

            selectData.value = {}
            isRepeat.value = false
            formData.area = ''
            formData.minSale = ''
            formData.accessMode = ''
            formData.salesVolume = ''
            ruleForm.value.resetFields()
            setTimeout(() => {
              ruleForm.value.clearValidate()
            }, 100)
          }
        })
      }

      const dialogConfirm = () => {
        if (selectData.value.errorStatus) {
          currentInstance.proxy.customMessage({type: 'error', message: errMap.value[selectData.value.errorStatus]})
          return
        } else if (isRepeat.value) {
          currentInstance.proxy.customMessage({type: 'error', message: '终端已添加'})
          return
        }
        ruleForm.value.validate((val) => {
          if (val) {
            formData.exploitPrice = '¥' + formData.devEarnestMoney
            formData.devEarnestMoney = Number(formData.devEarnestMoney)
            if (formData.sellEarnestMoney) {
              formData.salesStr = '¥' + formData.sellEarnestMoney
            }
            formData.sellEarnestMoney = Number(formData.sellEarnestMoney)
            formData.minSale = Number(formData.minSale)
            formData.terminalPrice = Number(formData.terminalPrice)

            emit('confirm', {...formData})
            handleClose()
          }
        })
      }

      const dateChange = () => {
        if (formData.date) {
          formData.expireTime = formData.date
        }// currentInstance.proxy.dateFormat('yyyy-mm-dd HH:MM:SS',formData.date)
      }

      const getAreaCode = () => {
        let a = {
          provinceCode: [],
          cityCode: [],
          areaCode: []
        }
        for (let i = 0; i < props.propsProduct.region.length; i++) {
          let area = props.propsProduct.region[i]
          if (area.level == 1) {
            a.provinceCode.push(area.regionCode)
          }
          if (area.level == 2) {
            a.cityCode.push(area.regionCode)
          }
          if (area.level == 3) {
            a.areaCode.push(area.regionCode)
          }
        }
        return a
      }

      const querySearchAsync = (queryString, cb) => {
        // selectData.value = null
        isRepeat.value = false

        if (!queryString) {
          cb([])
          return
        }
        const data = {
          id: props.id,
          terminalName: queryString,
          listType: 2,
          region:props.propsProduct.region,
          terminalType:props.propsProduct.terminalType,
          ...getAreaCode()
        }

        api.plan.PLAN_TERMINAL_DOWN_LIST(data).then(res => {
          if (!res.code) {
            if (res.data.list) {
              if (res.data.list.length){
                res.data.list.forEach(item => {
                  item.value = item.terminalName
                })
              }
              cb(res.data.list)
            }
          } else {
            currentInstance.proxy.customMessage({type: 'error', message: res.msg})
            cb([])
          }
        })
      }

      const checkTerminal = (id) => {
        const data = {
          terminalId: id,
          modelType: 2,
          ifOne:true,
          areaSelectType: false,
          region:props.propsProduct.region,
          terminalType:props.propsProduct.terminalType,
          productId: props.propsProduct.productId
        }

        api.common.TERMINAL_CHECK_TERMINAL(data).then(res => {
          if (!res.code) {
            if (res.data.list && res.data.list.terminalList) {
              res.data.list.terminalList.forEach(item => {
                item.value = item.terminal.terminalName
              })
              errMap.value = res.data.list.errMap
              selectData.value = res.data.list.terminalList[0]
            }
          } else {
          }
        })
      }

      const createFilter = (queryString) => {
        return (restaurant) => {
          return (
                  restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) != -1
          )
        }
      }

      const openDialog = () => {
        if (props.propsProduct.minSale) {
          formData.minSale = props.propsProduct.minSale
          formData.minSaleUnit = props.propsProduct.minSaleUnit
        }
        if (props.propsProduct.minSalePromise) {
          formData.sellEarnestMoney = props.propsProduct.minSalePromise
        }
        data.copyData = {...props.propsProduct}
        selectData.value = {}
        dialogVisible.value = true
      }

      const handleSelect = (item) => {
        if (props.list.findIndex(a => a.terminalId == item.id) != -1) {
          isRepeat.value = true
        } else {
          isRepeat.value = false
        }

        // formData.id = item.terminal.id
        formData.terminalId = item.id
        formData.terminalName = item.value
        formData.terminalType = item.terminalType
        formData.area = ''
        if (item.provinceName) {
          formData.area = item.provinceName
        }
        if (item.cityName) {
          formData.area = formData.area + '/' + item.cityName
        }
        if (item.areaName) {
          formData.area = formData.area + '/' + item.areaName
        }
        data.copyData.terminalId = item.id
        data.copyData.terminalType = item.terminalType

        checkTerminal(item.id)
      }

      const nameBlur = () => {
        if (selectData.value) {
          formData.terminalName = selectData.value.value
        }
      }

      const salesBlur = (row) => {
        if (formData.minSale) {
          formData.minSale = Number(formData.minSale)
        } else {
          formData.minSale = 0
        }
      }

      const salesPriceBlur = (row) => {
        if (formData.sellEarnestMoney) {
          formData.salesStr = '¥' + formData.sellEarnestMoney
          formData.sellEarnestMoney = Number(formData.sellEarnestMoney)
        } else {
          formData.salesStr = ''
          formData.sellEarnestMoney = 0
        }
      }

      const priceConfirm = (val) => {
        formData.productPriceId = val.id
        formData.terminalPrice = Number(val.terminalPrice)
        formData.accessMode = val.accessMode
      }

      const priceFocus = (val) => {
        if (val) {
          pricePop.value.openPopover()
        } else {

        }
      }

      const priceClear = () => {
        formData.productPriceId = 0
        formData.terminalPrice = 0
        formData.accessMode = ''
      }

      return {
        ...toRefs(data),
        ruleForm,
        dialogVisible,
        rules,
        formData,
        options,
        errMap,
        selectData,
        isRepeat,
        pricePop,
        sellOptions,

        handleClose,
        dialogConfirm,
        openDialog,
        querySearchAsync,
        handleSelect,
        dateChange,
        salesBlur,
        salesPriceBlur,
        addClick,
        nameBlur,
        priceConfirm,
        priceFocus,
        priceClear,
        disabledDate,
      }
    }
  })
</script>

<style lang="scss">

  .add-app-dialog {
    .el-autocomplete {
      width: 100%;
    }

    .el-input {
      width: 100%;
    }

    .specail-input {
      display: flex;

      .el-input__inner {
        border-radius: 5px 0 0 5px;
      }

      .el-select {
        width: 110px;

        .el-input__inner {
          border-radius: 0 5px 5px 0;
          border-left: 0;
        }
      }
    }
  }
</style>

